#!/bin/bash -e
source reporting.sh
REPORT=/tmp/report.txt
LOCAL_REPORT=tmp/report.txt
MANIFEST=./module_manifest.json
MONO_LOG=/tmp/monolog.switch.txt
RESULT_LINES=/tmp/results.switch.txt

# Setup for accessing control plane switch. If LOCAL_IP is defined, which
# is the intended local address for this node on the control plane then
# SWITCH_IP will be the IP address of the OpenFlow switch.

if [ -n "$LOCAL_IP" ]; then
    echo Configuring network with local address $LOCAL_IP.
    ip addr add $LOCAL_IP dev `hostname`-eth0
    echo Switch Test with model $SWITCH_MODEL.
    echo Switch test with port $SWITCH_PORT.
    ping -n -c 10 $SWITCH_IP
    POE_ENABLED=`jq -r .modules.switch.poe.enabled /config/device/module_config.json`
    java -jar switches/target/switchtest-0.0.1-jar-with-dependencies.jar $SWITCH_IP $SWITCH_PORT $POE_ENABLED $SWITCH_MODEL

    grep -v "RESULT" $LOCAL_REPORT | tee -a $MONO_LOG
    grep "RESULT" $LOCAL_REPORT | tee -a $RESULT_LINES

    write_out_monolog $REPORT \
                      $MANIFEST \
                      $MONO_LOG \
                      $RESULT_LINES
 
else

    SKIP_REASON="LOCAL_IP not configured, assuming no network switch."
    RESULT="skip"
    SUMMARY="No local IP has been set, check ext_loip in system.conf"

    write_out_result $REPORT \
                     "connection.port_link" \
                     "$(jq -r '.["connection.port_link"].description' $MANIFEST)" \
                     "$SKIP_REASON" \
                     "RESULT $RESULT connection.port_link $SUMMARY"

    write_out_result $REPORT \
                     "connection.port_speed" \
                     "$(jq -r '.["connection.port_speed"].description' $MANIFEST)" \
                     "$SKIP_REASON" \
                     "RESULT $RESULT connection.port_speed $SUMMARY"

    write_out_result $REPORT \
                     "connection.port_duplex" \
                     "$(jq -r '.["connection.port_duplex"].description' $MANIFEST)" \
                     "$SKIP_REASON" \
                     "RESULT $RESULT connection.port_duplex $SUMMARY"

    write_out_result $REPORT \
                     "poe.power" \
                     "$(jq -r '.["poe.power"].description' $MANIFEST)" \
                     "$SKIP_REASON" \
                     "RESULT $RESULT poe.power $SUMMARY"

    write_out_result $REPORT \
                     "poe.negotiation" \
                     "$(jq -r '.["poe.negotiation"].description' $MANIFEST)" \
                     "$SKIP_REASON" \
                     "RESULT $RESULT poe.negotiation $SUMMARY"

    write_out_result $REPORT \
                     "poe.support" \
                     "$(jq -r '.["poe.support"].description' $MANIFEST)" \
                     "$SKIP_REASON" \
                     "RESULT $RESULT poe.support $SUMMARY"

fi
